<template>
  <div class="gl_contentBox gl_heightFull">
    <p style="border-bottom:1px solid rgba(0, 0, 0, 0.1);padding:4px">{{ this.$route.query.id ? '编辑模板' : '新建模板' }}</p>
    <el-row>
      <el-col :span="12">
        <el-form
          v-if="!loading"
          ref="addTemplateInputForm"
          label-width="100px"
          :rules="AddTemplate_Rules"
          :model="addTemplateInput"
          size="mini"
        >
          <div style="padding: 15px">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model.trim="addTemplateInput.name" size="small" style="width:390px" />
            </el-form-item>
            <el-form-item label="模板类型" prop="messageTemplateTypeCode">
              <el-select v-model="addTemplateInput.messageTemplateTypeCode" size="mini" @change="composeQueryData">
                <el-option v-for="(item,index) in dict.messageTemplateType" :key="index" :value="item.code" :label="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="模板消息类型" prop="checkList">
              <el-checkbox-group v-model="checkList" @change="onCheckBoxChange">
                <el-checkbox v-for="(item, index) in dict.messageTemplateStyleType" :key="index" :value="item.code" :label="item.code">{{ item.value }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-show="styleShow && checkList.indexOf('H5') !== -1" label="H5">
              <el-select v-model="activeH5" value-key="id" placeholder="模板类型" filterable @change="choooseTempType($event, 'H5')">
                <el-option v-for="item in H5TemplateList" :key="item.id" :value="item" :label="item.name" />
              </el-select>
              <a v-show="activeH5.imageUrl" class="preview_btn" @click="previewTemp('H5')">预览</a>
            </el-form-item>
            <!-- <el-form-item v-show="activeH5.imageUrl">
              <img class="preview_img" :src="getStaticUrl(activeH5.imageUrl)" alt="预览图">
            </el-form-item> -->
            <el-form-item v-show="styleShow && checkList.indexOf('Text') !== -1" label="纯文字" prop="messageTemplateTextStyleId">
              <el-select v-model="activeText" value-key="id" placeholder="模板类型" filterable @change="choooseTempType($event, 'Text')">
                <el-option v-for="item in TextTemplateList" :key="item.id" :value="item" :label="item.name" />
              </el-select>
              <!-- <a v-show="activeText.stringFormat" class="preview_btn" @click="previewTemp('Text')">预览</a> -->
            </el-form-item>
            <el-form-item v-show="activeText.stringFormat">
              <div class="preview_text">{{ activeText.stringFormat && activeText.mockDataJson ? replaceStrByObj(activeText.stringFormat, JSON.parse(activeText.mockDataJson)) : '' }}</div>
            </el-form-item>
          </div>
        </el-form>
        <div style="text-align:left; padding-left: 120px;">
          <span class="anniu">
            <el-button size="mini" @click="goBack">取消</el-button>
            <el-button type="primary" :loading="submitLoading" size="mini" @click="submitAddTemplate()">确 定</el-button>
          </span>
        </div>
      </el-col>
      <el-col v-show="activeH5.imageUrl" :span="12">
        <p style="padding: 15px 0;font-weight: bold;">H5模板样式预览</p>
        <div v-show="activeH5.imageUrl">
          <!-- <img class="preview_img" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" alt="预览图"> -->
          <img class="preview_img" :src="getStaticUrl(activeH5.imageUrl)" alt="预览图">
        </div>
      </el-col>
    </el-row>

    <!-- 新建模板弹窗 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="800px"
      title="模板预览"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div style="width: 760px; height: 1610px; margin: auto">
        <iframe width="760px" height="100%" :src="getStaticUrl(previewUrl)" frameborder="1" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { FormatDate } from '@/lib';
import {
  api_POST_ClubMessageTemplate, // 创建模板
  api_GET_ClubMessageTemplateMessageTemplateStyles, // 获取模板样式列表
  api_GET_ClubMessageTemplateId, // 获取模板
  api_PUT_ClubMessageTemplateId, // 更新模板
  api_GET_ClubMessageTemplateIdMessageTemplateStyle // 获取样式
} from '@/extend/api/hallswaggerApi/app.js';
import {
  CreateMessageTemplateInput,
  Api_GET_ClubMessageTemplateMessageTemplateStylesQO,
  Api_GET_ClubMessageTemplateIdQO
} from '@/lib/form/hall/swaggerForm';
import { AddTemplate_Rules } from '@/lib/validate/hall/index.js';
export default {
  data() {
    return {
      loading: false,
      addTemplateDialog: false,
      addDialogLoading: false,
      infoQO: new Api_GET_ClubMessageTemplateIdQO(),
      addTemplateInput: new CreateMessageTemplateInput(),
      qo: new Api_GET_ClubMessageTemplateMessageTemplateStylesQO(),
      AddTemplate_Rules: new AddTemplate_Rules(),
      H5TemplateList: [],
      TextTemplateList: [],
      activeId: null,
      checkList: [],
      styleShow: false,
      activeH5: '',
      activeText: '', // 当前选中的文本模板
      // 模板预览
      dialogVisible: false,
      previewUrl: '',
      submitLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  watch: {
    checkList: {
      deep: true,
      handler(val, oldVal) {
        console.log(val, '==数据==');
        if (val.length > 0) {
          this.onCheckBoxChange(val);
        }
        if (val.indexOf('H5') === -1) {
          this.addTemplateInput.messageTemplateH5StyleId = null;
          this.activeH5 = {};
          this.H5TemplateList = [];
        }
        if (val.indexOf('Text') === -1) {
          this.addTemplateInput.messageTemplateTextStyleId = null;
          this.activeText = {};
          this.TextTemplateList = [];
        }
      }
    }
  },
  mounted() {
    // 是否编辑模板
    if (this.$route.query.id) {
      this.activeId = this.$route.query.id;
      this.getTemplateInfo();
    }
    this.getDict();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取模板详情
    getTemplateInfo() {
      this.loading = true;
      this.infoQO.IncludeMessageTemplateType = true;
      this.infoQO.IncludeMessageTemplateStyle = true;
      api_GET_ClubMessageTemplateId(this.activeId, this.infoQO).then(
        res => {
          if (res) {
            this.loading = false;
            this.addTemplateInput = res;
            this.qo.MessageTemplateTypeCode = res.messageTemplateTypeCode;
            this.handleEditData(res);
          }
        },
        error => {
          this.loading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 获取模板样式
    getTemplateStyle(id, type) {
      api_GET_ClubMessageTemplateIdMessageTemplateStyle(id, {
        IncludeMessageTemplateType: true,
        IncludeMessageTemplateStyleType: true
      }).then(
        res => {
          this['active' + type] = res;
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 编辑时给chekList赋值
    handleEditData(obj) {
      this.checkList = [];
      if (obj.messageTemplateH5StyleId) {
        this.checkList.push('H5');
        this.getTemplateStyle(obj.messageTemplateH5StyleId, 'H5');
        // this.activeH5 = obj.messageTemplateH5Style;
      }
      if (obj.messageTemplateTextStyleId) {
        this.checkList.push('Text');
        this.getTemplateStyle(obj.messageTemplateTextStyleId, 'Text');
        // this.activeH5 = obj.messageTemplateTextStyle;
      }
    },
    // 选择模板类型
    onCheckBoxChange(val) {
      this.$nextTick(() => {
        this.$refs['addTemplateInputForm'].validate(valid => {
          if (valid) {
            if (val.length > 0) {
              if (val.length === 2) {
                this.qo.MessageTemplateStyleTypeCode = '';
                this.getTemplateTypeList(val);
              } else {
                this.qo.MessageTemplateStyleTypeCode = val[0];
                this.getTemplateTypeList();
              }
            }
          } else {
            this.checkList = [];
          }
        });
      });
    },
    // 获取模板样式
    getTemplateTypeList() {
      this.qo.IncludeMessageTemplateType = true;
      this.qo.IncludeMessageTemplateStyleType = true;
      api_GET_ClubMessageTemplateMessageTemplateStyles(this.qo).then(
        res => {
          if (res) {
            this.qo.MessageTemplateStyleTypeCode = '';
            this.filterTypeData(res);
            this.styleShow = true;
          }
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 模板样式分类
    filterTypeData(arr) {
      this.H5TemplateList = [];
      this.TextTemplateList = [];
      arr.map(item => {
        if (item.messageTemplateStyleTypeCode === 'H5') {
          this.H5TemplateList.push(item);
        } else if (item.messageTemplateStyleTypeCode === 'Text') {
          this.TextTemplateList.push(item);
        }
      });
    },
    // 根据模板类型查询模板样式
    composeQueryData(val) {
      this.checkList = [];
      this.qo.MessageTemplateTypeCode = val;
      this.getTemplateTypeList();
    },
    // 选择相对应的模板
    choooseTempType(event, type) {
      console.log(event, type);
      this['active' + type] = event;
      this.addTemplateInput['messageTemplate' + type + 'StyleId'] = event.id;
    },
    // 预览
    previewTemp(type) {
      if (this['active' + type].imageUrl) {
        this.previewUrl = this['active' + type].imageUrl;
        this.dialogVisible = true;
      } else {
        this.$message({ type: 'error', message: '没有预览图，无法进行预览' });
      }
    },
    // 替换字符串模板
    replaceStrByObj (str, obj) {
      obj.CheckInTime = obj.CheckInTime ? FormatDate(obj.CheckInTime, 'yyyy-MM-dd HH:mm:ss') : '';
      obj.CheckOutTime = obj.CheckOutTime ? FormatDate(obj.CheckOutTime, 'yyyy-MM-dd HH:mm:ss') : '';
      obj.CreationTime = obj.CreationTime ? FormatDate(obj.CreationTime, 'yyyy-MM-dd HH:mm:ss') : '';
      obj.BeginDate = obj.BeginDate ? FormatDate(obj.BeginDate, 'yyyy-MM-dd HH:mm:ss') : '';
      obj.EndDate = obj.EndDate ? FormatDate(obj.EndDate, 'yyyy-MM-dd HH:mm:ss') : '';
      let _str = str;
      for (const k in obj) {
        _str = _str.replace(new RegExp('\\{' + k + '\\}', 'g'), obj[k]);
      }
      console.log('str', _str);
      return _str;
    },
    // 确认新建
    submitAddTemplate() {
      this.$refs['addTemplateInputForm'].validate(valid => {
        if (valid) {
          this.judgeTempType();
        }
      });
    },
    // 判断是否选择相对应的模板类型
    judgeTempType() {
      const length = this.checkList.length;
      switch (length) {
        case 0: this.$message({ type: 'error', message: '请选择模板消息类型' });
          break;
        case 1: {
          const id = this.addTemplateInput['messageTemplate' + this.checkList[0] + 'StyleId'];
          if (id && id !== '') {
            this.insertTemplate();
          } else {
            this.$message({ type: 'error', message: '请选择模板消息类型' });
          }
          break;
        }
        case 2: {
          if (
            this.addTemplateInput.messageTemplateTextStyleId === null ||
            this.addTemplateInput.messageTemplateTextStyleId === '' ||
            this.addTemplateInput.messageTemplateH5StyleId === null ||
            this.addTemplateInput.messageTemplateH5StyleId === '') {
            this.$message({ type: 'error', message: '请选择模板消息类型' });
          } else {
            this.insertTemplate();
          }
        }
      }
    },
    insertTemplate() {
      this.submitLoading = true;
      if (this.activeId) {
        // 更新模板
        api_PUT_ClubMessageTemplateId(this.activeId, this.addTemplateInput).then(
          () => {
            this.$message({
              message: '更新成功',
              type: 'success'
            });
            this.submitLoading = false;
            this.goBack();
          },
          error => {
            this.submitLoading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          }
        );
      } else {
        // 新建模板
        api_POST_ClubMessageTemplate(this.addTemplateInput).then(
          () => {
            this.$message({
              message: '创建成功',
              type: 'success'
            });
            this.submitLoading = false;
            this.goBack();
          },
          error => {
            this.submitLoading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          }
        );
      }
    },
    // 返回
    goBack() {
      this.$router.push({
        name: 'InfoTempManage'
      });
    },
    // 获取静态文件
    getStaticUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_TEMPLATE_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
.gl_contentBox {
  box-sizing: border-box;
}
.title {
  height: 36px;
  line-height: 23px;
  font-size: 16px;
  font-weight: 600;
  font-family: PingFang SC, PingFang SC-Medium;
  padding-left: 9px;
  border-bottom: 2px solid #ddd;
  color: rgba(0, 0, 0, .85)
}
.content_box {
  margin: 10px auto;
  .content_title {
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    font-weight: 500;
    font-family: PingFang SC, PingFang SC-Regular;
    color: #000000;
  }
  .forms{
    width: 700px;
    .el-form-item__label{
      font-size: 16px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #353434;
    }
  }
  .radiobox {
    height: 50px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .radioOne {
      width: 36px;
      height: 36px;
      border-radius: 2px;
      margin-right: 15px;
    }
    .oneBorder {
      border: 2px solid #1990FF;
    }
  }
  .classType {
    .el-form-item__content {
      height: 80px;
    }
  }
}
.submitIt {
  margin: 30px 0px 0px 300px;
}
.preview_img {
  width: 375px;
  // height: 420px;
  height: auto;
  border-radius: 6px;
  cursor: pointer;
}
.preview_btn {
  padding-left: 15px;
  color: #409eff;
}
/* swiper */
.swiper-container {
  width: 100%;
  height: 420px;
  border-radius: 6px;
}
.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;
  height: 420px;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  border-radius: 6px;
  overflow: hidden;
}
.h5_swiper {
  height: 420px;
}
.img_style {
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.no_tag {
  padding-left: 15px;
  color: #C0C4CC;
  font-size: 12px;
}
.active {
  box-shadow: 0px 0px 10px red;
}
.icon-active {
  width: 25px;
  height: 25px;
  position: absolute;
  bottom: 0;
  right: 48px;
  background: red;
  color: #fff;
  font-size: 25px;
  z-index: 9999;
  border-bottom-right-radius: 6px;
}
.success_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #14CE67;
  border-radius: 50%;
}
.error_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #FF3434;
  border-radius: 50%;
}
.nav {
  margin-left: 203px;
  margin-top: 58px;
}
.preview_text {
  width: 450px;
  height: 150px;
  min-height: 150px;
  border: 1px solid #C0C4CC;
  border-radius: 4px; padding: 10px;
}
</style>
